package main

//54. 螺旋矩阵
func main() {
	arr := [][]int{
		{1, 2, 3}, {4, 5, 6}, {7, 8, 9},
	}

	order := spiralOrder(arr)

	for _, i := range order {
		print(i, " ")
	}

}

func spiralOrder(matrix [][]int) []int {
	var res []int

	if len(matrix) == 0 || matrix[0] == nil {
		return res
	}

	m := len(matrix)
	n := len(matrix[0])

	top, bottom, left, right := 0, m-1, 0, n-1

	for top <= bottom && left <= right {
		for i := left; i <= right; i++ {
			res = append(res, matrix[top][i])
		}
		for i := top + 1; i <= bottom; i++ {
			res = append(res, matrix[i][right])
		}
		if left < right && top < bottom {
			for i := right - 1; i >= left; i-- {
				res = append(res, matrix[bottom][i])
			}
			for i := bottom - 1; i > top; i-- {
				res = append(res, matrix[i][left])
			}
		}
		top++
		left++
		bottom--
		right--
	}

	return res
}

// 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
//
//示例 1：
//
//输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
//输出：[1,2,3,6,9,8,7,4,5]
//示例 2：
//
//输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
//输出：[1,2,3,4,8,12,11,10,9,5,6,7]
//
//提示：
//
//m == matrix.length
//n == matrix[i].length
//1 <= m, n <= 10
//-100 <= matrix[i][j] <= 100
